package com.cucn.ingmall.seckill.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.cucn.common.constant.seckill.SeckillConstant;
import com.cucn.common.to.dto.MemberResponseDTO;
import com.cucn.common.to.mq.SeckillOrderTO;
import com.cucn.common.utils.R;
import com.cucn.ingmall.seckill.dto.SeckillSessionDTO;
import com.cucn.ingmall.seckill.dto.SkuInfoDTO;
import com.cucn.ingmall.seckill.feign.CouponFeignService;
import com.cucn.ingmall.seckill.feign.ProductFeignService;
import com.cucn.ingmall.seckill.interceptor.LoginUserInterceptor;
import com.cucn.ingmall.seckill.service.SeckillService;
import com.cucn.ingmall.seckill.to.SeckillSkuRedisTO;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @author KouChaoJie
 * @since: 2022/2/13 17:24
 */
@Service
@Slf4j
public class SecKillServiceImpl implements SeckillService {
    @Resource
    private CouponFeignService couponFeignService;
    @Resource
    private ProductFeignService productFeignService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private RedissonClient redissonClient;
    @Resource
    private RabbitTemplate rabbitTemplate;

    public static final String SESSIONS_CACHE_PREFIX = "seckill:sessions:";
    public static final String SKUKILL_CACHE_PREFIX = "seckill:skus";
    /**
     * +商品随机码
     */
    public static final String SKU_STOCK_SEMAPHORE = "seckill:stock:";

    @Override
    public void uploadSeckillLastThreeDays() {
        //1.扫描需要最近三天参与秒杀的活动
        //远程调用优惠服务
        R rCoupon = couponFeignService.getLastThreeDays();
        if (rCoupon.getCode() == 0) {
            List<SeckillSessionDTO> seckillSessions = rCoupon.getData(new TypeReference<List<SeckillSessionDTO>>() {
            });

            //将查出的信息缓存到redis
            //1.缓存活动信息
            saveSessionInfos(seckillSessions);
            //2.缓存活动商品信息
            saveSessionSkuInfos(seckillSessions);
        }
    }


    public List<SeckillSkuRedisTO> blockHandler() {
        log.error("getCurrentSeckillSkusResource被限流了");
        return null;
    }

    @Override
    @SentinelResource(value = "getCurrentSeckillSkusResource", blockHandler = "blockHandler")
    public List<SeckillSkuRedisTO> getCurrentSeckillSkus() {
        //确定当前时间属于哪个场次
        long currentTime = new Date().getTime();
        try (Entry entry = SphU.entry("seckillSkus")) {
            Set<String> keys = stringRedisTemplate.keys(SESSIONS_CACHE_PREFIX + "*");
            if (keys != null) {
                for (String key : keys) {
                    String replace = key.replace(SESSIONS_CACHE_PREFIX, "");
                    String[] timeArr = replace.split("_");
                    long startTime = Long.parseLong(timeArr[0]);
                    long endTime = Long.parseLong(timeArr[1]);

                    if (currentTime >= startTime && currentTime <= endTime) {
                        //查询当前场次
                        List<String> sessions = stringRedisTemplate.opsForList().range(key, -100L, 100L);

                        BoundHashOperations<String, String, String> ops = stringRedisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
                        List<String> skus = ops.multiGet(sessions);

                        if (CollectionUtil.isNotEmpty(skus)) {
                            List<SeckillSkuRedisTO> seckillSKus = skus.stream().map(item -> {
                                SeckillSkuRedisTO seckillSkuRedisTO = JSON.parseObject(String.valueOf(item), SeckillSkuRedisTO.class);
                                //当前秒杀开始了,需要随机码
                                return seckillSkuRedisTO;
                            }).collect(Collectors.toList());
                            return seckillSKus;
                        }

                        break;
                    }
                }
            }
        } catch (BlockException e) {
            log.error("资源被限流...", e);
        }

        return null;
    }

    @Override
    public SeckillSkuRedisTO getSkuSeckillInfo(Long skuId) {
        BoundHashOperations<String, String, String> ops = stringRedisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
        Set<String> keys = ops.keys();
        if (CollectionUtil.isNotEmpty(keys)) {
            //正则匹配
            String regx = "[0-9]*_" + skuId;
            for (String key : keys) {
                if (Pattern.matches(regx, key)) {
                    String json = ops.get(key);
                    SeckillSkuRedisTO skuRedisTO = JSON.parseObject(json, SeckillSkuRedisTO.class);

                    if (ObjectUtil.isNotEmpty(skuRedisTO)) {
                        long currentTime = new Date().getTime();
                        long startTime = skuRedisTO.getStartTime();
                        long endTime = skuRedisTO.getEndTime();
                        if (!(currentTime >= startTime && currentTime <= endTime)) {
                            skuRedisTO.setRandomCode(null);
                        }
                    } else {
                        return null;
                    }

                    return skuRedisTO;
                }
            }
        }

        return null;
    }

    @Override
    public String kill(String killId, String key, Integer num) {
        long s1 = System.currentTimeMillis();
        //当前登录用户
        MemberResponseDTO member = LoginUserInterceptor.loginUser.get();

        //1.获取当前秒杀商品的详细信息
        BoundHashOperations<String, Object, Object> hashOps = stringRedisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);

        String skuKillInfoRedisJsonString = (String) hashOps.get(killId);
        if (StringUtils.isEmpty(skuKillInfoRedisJsonString)) {
            return null;
        } else {
            SeckillSkuRedisTO skuKillInfo = JSONObject.parseObject(skuKillInfoRedisJsonString, SeckillSkuRedisTO.class);
            //校验合法性
            //秒杀时间
            long currentTime = new Date().getTime();
            long startTime = skuKillInfo.getStartTime();
            long endTime = skuKillInfo.getEndTime();
            long ttl = endTime - startTime;
            if (currentTime >= startTime && currentTime <= endTime) {
                //校验随机码与对应关系
                String randomCode = skuKillInfo.getRandomCode();
                String killIdInfo = skuKillInfo.getPromotionSessionId() + "_" + skuKillInfo.getSkuId();

                if (randomCode.equals(key) && killIdInfo.equals(killId)) {
                    //数量
                    int killNum = skuKillInfo.getSeckillLimit().intValue();
                    if (killNum <= num) {
                        //验证这个人是否已经购买过。幂等性;只要秒杀成功,就去占位; userId_SessionId_skuId
                        String nxKey = member.getId() + "_" + killId;
                        //占位时间在秒杀场次结束后清除,设置过期时间
                        Boolean ifAbsent = stringRedisTemplate.opsForValue().setIfAbsent(nxKey, num.toString(), ttl, TimeUnit.MILLISECONDS);
                        if (Boolean.TRUE.equals(ifAbsent)) {
                            //占位成功说明该次秒杀第一次购买
                            //合法性校验完成,获取分布式库存信号量
                            RSemaphore stockSemaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + randomCode);
                            //尝试从库存信号量中扣减秒杀件数
                            try {
                                boolean hasStock = stockSemaphore.tryAcquire(num, 100, TimeUnit.MILLISECONDS);
                                //秒杀成功
                                //快速下单,发送mq消息,创建订单
                                if (hasStock) {
                                    String orderSn = IdWorker.getTimeId();
                                    SeckillOrderTO seckillOrderTO = new SeckillOrderTO();
                                    seckillOrderTO.setOrderSn(orderSn);
                                    seckillOrderTO.setNum(num);
                                    seckillOrderTO.setMemberId(member.getId());
                                    seckillOrderTO.setSeckillPrice(skuKillInfo.getSeckillPrice());
                                    seckillOrderTO.setPromotionSessionId(seckillOrderTO.getPromotionSessionId());
                                    seckillOrderTO.setSkuId(skuKillInfo.getSkuId());
                                    //发送消息
                                    rabbitTemplate.convertAndSend(SeckillConstant.ORDER_EVENT_EXCHANGE, SeckillConstant.ORDER_SECKILL_ORDER_ROUTING_KEY, seckillOrderTO);
                                    long s2 = System.currentTimeMillis();
                                    log.info("耗时:{}", s2 - s1);
                                    return orderSn;
                                } else {
                                    return null;
                                }
                            } catch (InterruptedException e) {
                                log.error("秒杀失败,秒杀商品的库存不足...", e);
                                return null;
                            }
                        } else {
                            return null;
                        }
                    } else {
                        return null;
                    }
                } else {
                    return null;
                }
            } else {
                return null;
            }
        }

    }

    /**
     * 缓存活动关联商品信息
     *
     * @param seckillSessions 秒杀活动信息
     */
    private void saveSessionSkuInfos(List<SeckillSessionDTO> seckillSessions) {
        seckillSessions.forEach(session -> {
            BoundHashOperations<String, Object, Object> boundHashOps = stringRedisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
            session.getSkuRelationList().forEach(sku -> {
                //随机码
                String randomCode = UUID.randomUUID().toString().replace("-", "");
                if (!boundHashOps.hasKey(sku.getPromotionSessionId().toString() + "_" + sku.getSkuId().toString())) {
                    //缓存商品
                    SeckillSkuRedisTO skuRedisTO = new SeckillSkuRedisTO();
                    //1.缓存sku的基本信息
                    R rSkuInfo = productFeignService.info(sku.getSkuId());
                    if (rSkuInfo.getCode() == 0) {
                        SkuInfoDTO skuInfo = rSkuInfo.getData("skuInfo", new TypeReference<SkuInfoDTO>() {
                        });
                        skuRedisTO.setSkuInfo(skuInfo);
                    }
                    skuRedisTO.setStartTime(session.getStartTime().getTime());
                    skuRedisTO.setEndTime(session.getEndTime().getTime());

                    skuRedisTO.setRandomCode(randomCode);

                    //2.缓存sku的秒杀信息
                    BeanUtils.copyProperties(sku, skuRedisTO);

                    String skuString = JSON.toJSONString(skuRedisTO);
                    boundHashOps.put(sku.getPromotionSessionId().toString() + "_" + sku.getSkuId().toString(), skuString);

                    //如果当前这个场次的商品的库存信息已经上架就不需要上架
                    //使用库存作为分布式信号量:限流
                    RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + randomCode);
                    //商品可以秒杀的数量作为信号量
                    semaphore.trySetPermits(sku.getSeckillCount().intValue());
                }

            });
        });
    }

    /**
     * 缓存活动场次信息
     *
     * @param seckillSessions 秒杀活动信息
     */
    private void saveSessionInfos(List<SeckillSessionDTO> seckillSessions) {
        seckillSessions.forEach(session -> {
            long startTime = session.getStartTime().getTime();
            long endTime = session.getEndTime().getTime();
            String key = SESSIONS_CACHE_PREFIX + startTime + "_" + endTime;
            Boolean hasKey = stringRedisTemplate.hasKey(key);
            if (!hasKey) {
                List<String> skuIds = session.getSkuRelationList().stream().map(item -> item.getPromotionSessionId().toString() + "_" + item.getSkuId().toString()).collect(Collectors.toList());
                stringRedisTemplate.opsForList().leftPushAll(key, skuIds);
            }
        });
    }
}
